package org.inet.minispring;

import org.inet.minispring.bean.beandefinition.registry.BeanDefinitionRegistry;
import org.inet.minispring.bean.beanfactory.BeanFactory;
import org.inet.minispring.bean.beanfactory.SimpleBeanFactory;
import org.inet.minispring.bean.beanregistry.SingletonBeanRegistry;
import org.inet.minispring.consts.XMLBeanTagConstant;
import org.inet.minispring.exception.InitApplicationContextFailException;
import org.inet.minispring.resource.ClassPathXmlResource;
import org.inet.minispring.resource.Resource;

public class XmlBeanDefinitionReader {

    BeanFactory beanFactory;

    BeanDefinitionRegistry beanDefinitionRegistry;

    public XmlBeanDefinitionReader(BeanFactory beanFactory, BeanDefinitionRegistry beanDefinitionRegistry) {
        this.beanFactory = beanFactory;
        this.beanDefinitionRegistry = beanDefinitionRegistry;
    }

    public void loadBeanDefinitions(Resource resource) {
        if (!(resource instanceof ClassPathXmlResource xmlResource)) {
            throw new InitApplicationContextFailException("Resource should be ClassPathXmlResource");
        }
        while (xmlResource.hasNext()) {
            var element = xmlResource.next();
            String beanId = element.attributeValue(XMLBeanTagConstant.ATTRIBUTE_ID);
            String beanClassName = element.attributeValue(XMLBeanTagConstant.ATTRIBUTE_CLASS);
            var beanDefinition = new BeanDefinition(beanId, beanClassName);
            this.beanDefinitionRegistry.registerBeanDefinition(beanId, beanDefinition);
        }
    }
}
